#!/bin/bash
# OpenMPTCProuter VPS端一键安装脚本（优化版）
# 版本：v8.1 | 更新日期：2024-03-23

# 配置参数
SUPPORTED_KERNELS=("5.4" "6.1" "6.6")
OFFICIAL_SCRIPT="https://www.openmptcprouter.com/server/debian-x86_64.sh"
DOWNLOAD_PROXY=""
DEFAULT_KERNEL="6.1"

# 颜色定义
RED='\033[31m'; GREEN='\033[32m'; YELLOW='\033[33m'; RESET='\033[0m'

# 自动安装依赖
check_and_install_deps() {
  echo -e "${YELLOW}检查并安装必要的依赖...${RESET}"
  local packages=("curl" "wget" "gnupg2" "ufw" "jq" "lsb-release")
  for pkg in "${packages[@]}"; do
    if ! dpkg -l | grep -q "$pkg"; then
      echo -e "${YELLOW}安装 $pkg...${RESET}"
      apt install -y "$pkg"
    fi
  done
}

# 选择APT源
choose_mirror() {
  if [[ "$(lsb_release -cs)" == "bookworm" ]]; then
    while true; do
      echo -e "${YELLOW}是否更换APT源？${RESET}"
      echo "1) 163 源"
      echo "2) 清华源"
      echo "3) 阿里云源"
      echo "0) 不更换（默认）"
      read -p "请输入选项 (0/1/2/3): " choice < /dev/tty
      case "$choice" in
        1) SOURCE_URL="https://gitee.com/t88t/test/raw/master/debian12-163-sources.list"; break ;;
        2) SOURCE_URL="https://gitee.com/t88t/test/raw/master/debian12-tsinghua-sources.list"; break ;;
        3) SOURCE_URL="https://gitee.com/t88t/test/raw/master/debian12-aliyun-sources.list"; break ;;
        0) echo -e "${BLUE}跳过更换APT源。${RESET}"; return ;;
        *) echo -e "${RED}无效输入，请重新选择！${RESET}" ;;
      esac
    done
    echo -e "${YELLOW}正在更换APT源...${RESET}"
    curl -sSL "$SOURCE_URL" -o /etc/apt/sources.list
    apt update
  fi
}

# 选择内核
choose_kernel() {
  while true; do
    echo -e "${YELLOW}请选择要安装的内核版本:${RESET}"
    echo "1) 5.4"
    echo "2) 6.1（默认）"
    echo "3) 6.6"
    read -p "请输入选项 (1/2/3): " choice < /dev/tty
    case "$choice" in
      1) KERNEL="5.4"; break ;;
      2) KERNEL="6.1"; break ;;
      3) KERNEL="6.6"; break ;;
      *) echo -e "${RED}无效选择，请重新输入！${RESET}" ;;
    esac
  done
}

# 选择下载方式
choose_download_method() {
  while true; do
    echo -e "${YELLOW}请选择安装程序下载方式:${RESET}"
    echo "1) 直接下载（不使用加速，默认）"
    echo "2) 使用默认加速（ghproxy.com）"
    echo "3) 输入自定义加速链接"
    read -p "请输入选项 (1/2/3): " choice < /dev/tty
    case "$choice" in
      1) DOWNLOAD_PROXY=""; break ;;
      2) DOWNLOAD_PROXY="https://ghproxy.com/"; break ;;
      3) 
        read -p "请输入自定义加速链接: " custom_proxy < /dev/tty
        DOWNLOAD_PROXY="$custom_proxy"
        break ;;
      *) echo -e "${RED}无效选择，请重新输入！${RESET}" ;;
    esac
  done
}

# 更新 GitHub Hosts
update_github_ip() {
  echo -e "${YELLOW}正在更新 GitHub 的 IP 地址...${RESET}"
  GITHUB_IPS=$(curl -s https://api.github.com/meta | jq -r '.git[]')
  if [[ -z "$GITHUB_IPS" ]]; then
    echo -e "${RED}无法获取 GitHub 最新 IP，跳过更新 /etc/hosts${RESET}"
    return
  fi
  for ip in $GITHUB_IPS; do
    sed -i "/github.com/d" /etc/hosts
    echo "$ip github.com" >> /etc/hosts
    echo "$ip objects.githubusercontent.com" >> /etc/hosts
    echo "$ip raw.githubusercontent.com" >> /etc/hosts
  done
  echo -e "${GREEN}GitHub 的 IP 地址已更新！${RESET}"
}

# 下载官方安装脚本
download_script() {
  echo -e "${YELLOW}获取安装程序...${RESET}"
  local retries=3
  for ((i=1; i<=retries; i++)); do
    if curl -kL "${DOWNLOAD_PROXY}${OFFICIAL_SCRIPT}" -o /tmp/omr_install.sh; then
      return 0
    fi
    sleep $((i*2))
  done
  echo -e "${RED}安装脚本下载失败${RESET}" && exit 1
}

# 开放端口
open_required_ports() {
  echo -e "${YELLOW}是否开放 OpenMPTCPRouter 需要的所有端口？ (y/n)${RESET}"
  read -r answer < /dev/tty
  if [[ "$answer" == "y" ]]; then
    echo -e "${YELLOW}正在开放必要端口...${RESET}"
    REQUIRED_PORTS=(65222 65101 65280 65001 65500 65301 65201:65208 65400 65401 65228:65231 65248:65252 443 65311:65312)
    for port in "${REQUIRED_PORTS[@]}"; do
      ufw allow "$port"
    done
    ufw allow icmp  
    echo -e "${GREEN}所有必要端口已开放！${RESET}"
  else
    echo -e "${YELLOW}已跳过端口开放步骤。${RESET}"
  fi
}

# 主执行流程
main() {
  [[ $EUID -eq 0 ]] || { echo -e "${RED}需要 root 权限${RESET}"; exit 1; }
  [[ -e /dev/net/tun ]] || { echo -e "${RED}TUN 设备未启用${RESET}"; exit 1; }
  check_and_install_deps
  choose_mirror
  choose_kernel
  choose_download_method
  update_github_ip
  download_script
  echo -e "${YELLOW}安装 OpenMPTCPRouter (内核:$KERNEL)...${RESET}"
  chmod +x /tmp/omr_install.sh
  export DEBIAN_FRONTEND=noninteractive KERNEL
  /tmp/omr_install.sh || { echo -e "${RED}主安装流程失败${RESET}"; exit 1; }
  echo -e "${GREEN}[成功] 服务已启动！管理地址: http://$(curl -s icanhazip.com):8080${RESET}"
  open_required_ports
}

# 入口点
if [ -t 0 ]; then
  echo -e "${RED}请通过管道执行：curl -sSL URL | bash${RESET}"
  exit 1
else
  main "$@"
fi